package logic

import (
	"context"
	"platform/internal/svc"
	"platform/internal/types"
	"platform/proto/plugin"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type PluginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPluginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PluginLogic {
	return &PluginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// CallPlugin 调用插件处理请求
func (l *PluginLogic) CallPlugin(pluginName string, req *plugin.Request) (*plugin.Response, error) {
	// 设置超时上下文
	ctx, cancel := context.WithTimeout(l.ctx, 30*time.Second)
	defer cancel()

	// 调用插件管理器
	resp, err := l.svcCtx.PluginManager.CallPlugin(ctx, pluginName, req)
	if err != nil {
		l.Logger.Errorf("调用插件 %s 失败: %v", pluginName, err)
		return nil, err
	}

	l.Logger.Infof("插件 %s 调用成功, 状态码: %d", pluginName, resp.StatusCode)
	return resp, nil
}

// LoadPlugin 加载插件
func (l *PluginLogic) LoadPlugin(req *types.LoadPluginReq) (*types.LoadPluginResp, error) {
	if req.Name == "" || req.Path == "" {
		return nil, types.ErrInvalidParams
	}

	// 检查插件是否已经加载
	plugins := l.svcCtx.PluginManager.ListPlugins()
	for _, p := range plugins {
		if p == req.Name {
			return nil, types.ErrPluginAlreadyLoaded
		}
	}

	// 加载插件
	err := l.svcCtx.PluginManager.LoadPlugin(req.Name, req.Path)
	if err != nil {
		l.Logger.Errorf("加载插件 %s 失败: %v", req.Name, err)
		return nil, types.ErrLoadPluginFailed
	}

	// 获取插件信息
	info, err := l.svcCtx.PluginManager.GetPluginInfo(req.Name)
	if err != nil {
		l.Logger.Errorf("获取插件 %s 信息失败: %v", req.Name, err)
		return nil, types.ErrGetPluginInfo
	}

	return &types.LoadPluginResp{
		Success: true,
		Message: "插件加载成功",
		Plugin:  req.Name,
		Version: info.Version,
		Methods: info.Methods,
	}, nil
}

// UnloadPlugin 卸载插件
func (l *PluginLogic) UnloadPlugin(req *types.UnloadPluginReq) (*types.UnloadPluginResp, error) {
	if req.Name == "" {
		return nil, types.ErrInvalidParams
	}

	// 检查插件是否存在
	plugins := l.svcCtx.PluginManager.ListPlugins()
	found := false
	for _, p := range plugins {
		if p == req.Name {
			found = true
			break
		}
	}

	if !found {
		return nil, types.ErrPluginNotFound
	}

	// 卸载插件
	err := l.svcCtx.PluginManager.UnloadPlugin(req.Name)
	if err != nil {
		l.Logger.Errorf("卸载插件 %s 失败: %v", req.Name, err)
		return nil, types.ErrUnloadPluginFailed
	}

	return &types.UnloadPluginResp{
		Success: true,
		Message: "插件卸载成功",
		Plugin:  req.Name,
	}, nil
}

// ListPlugins 列出所有插件
func (l *PluginLogic) ListPlugins() (*types.ListPluginsResp, error) {
	plugins := l.svcCtx.PluginManager.ListPlugins()

	// 获取每个插件的详细信息
	pluginDetails := make([]types.PluginDetail, 0, len(plugins))
	for _, name := range plugins {
		info, err := l.svcCtx.PluginManager.GetPluginInfo(name)
		if err != nil {
			l.Logger.Errorf("获取插件 %s 信息失败: %v", name, err)
			continue
		}

		pluginDetails = append(pluginDetails, types.PluginDetail{
			Name:        name,
			Version:     info.Version,
			Description: info.Description,
			Methods:     info.Methods,
		})
	}

	return &types.ListPluginsResp{
		Plugins: pluginDetails,
		Count:   len(pluginDetails),
	}, nil
}

// HealthCheck 插件健康检查
func (l *PluginLogic) HealthCheck() (*types.HealthCheckResp, error) {
	ctx, cancel := context.WithTimeout(l.ctx, 10*time.Second)
	defer cancel()

	results := l.svcCtx.PluginManager.HealthCheck(ctx)

	healthStatus := make(map[string]types.HealthStatus)
	for plugin, healthy := range results {
		status := types.HealthStatus{
			Healthy: healthy,
			Message: "正常",
		}
		if !healthy {
			status.Message = "异常"
		}
		healthStatus[plugin] = status
	}

	return &types.HealthCheckResp{
		Status: healthStatus,
		Time:   time.Now().Unix(),
	}, nil
}
